package com.net.xpay.admin.controller.admin;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultData;
import com.net.common.model.ResultPagedList;
import com.net.common.util.SerializationUtil;
import com.net.xpay.common.domain.stat.UserSafePayTransStat;
import com.net.xpay.common.manager.stat.UserSafePayTransStatManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.model.UserSafePayTransStatSearchModel;
import com.net.xpay.core.utils.JxlsUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户安全付转账统计
 **/
@Slf4j
@RestController
@RequestMapping("/admin/user-safe-pay-trans-stat")
@Api(tags = "运营/用户安全付转账统计",description = "用户安全付转账统计")
public class AdminUserSafePayTransStatController {

    @Autowired
    private UserSafePayTransStatManager userSafePayTransStatManager;

    @ApiOperation(value = "用户安全付转账统计")
    @PostMapping(value = "/search")
    @PreAuthorize("hasAnyRole('ADMIN', 'user-safe-pay-trans-stat::search')")
    public ResultPagedList<UserSafePayTransStat> search(@RequestBody UserSafePayTransStatSearchModel searchModel){
        // 根据查询条件进行查询
        List<UserSafePayTransStat> userTransStatList = userSafePayTransStatManager.search(searchModel);
        // 查询带条件后数据的条数
        long count = userSafePayTransStatManager.searchCount(searchModel);
        return new ResultPagedList<>(userTransStatList,count,searchModel);

    }

    /**
     * 安全付转账统计记录导出
     */
    @ApiOperation("安全付转账统计记录导出")
    @GetMapping("/export")
    public ResultData<Boolean> exportSafePayTransStat(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, String searchModelJson) {
        Preconditions.checkArgument(searchModelJson != null);

        UserSafePayTransStatSearchModel searchModel = SerializationUtil.str2Object(searchModelJson, UserSafePayTransStatSearchModel.class);
        long count = userSafePayTransStatManager.searchCount(searchModel);
        if (count >= 10000L){
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "记录超过10000条，无法导出");
        }
        List<UserSafePayTransStat> userSafePayTransStatList = userSafePayTransStatManager.list(searchModel);

        // 定义一个Map，往里面放入要在模板中显示数据
        Map<String, Object> model = new HashMap<>();

        model.put("records", userSafePayTransStatList);

        String fileName = "安全付转账统计记录.xlsx";
        String template = "/excel/tpl/安全付转账统计记录.xls";

        InputStream is;
        try {
            //获取模板流
            is = getClass().getResourceAsStream(template);

            //火狐游览器中文文件名会有乱码,兼容火狐
            String agent = request.getHeader("USER-AGENT").toLowerCase();

            if (!Strings.isNullOrEmpty(agent) && (agent.contains("firefox") || agent.contains("safari"))) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            JxlsUtils.exportExcel(is, response.getOutputStream(), model);
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("export error", e);
        }
        return new ResultData<>();
    }

    /**
     * 安全付转账统计记录2导出
     */
    @ApiOperation("安全付转账统计记录2导出")
    @GetMapping("/export-two")
    public ResultData<Boolean> exportSafePayTransStatTwo(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, String searchModelJson) {
        Preconditions.checkArgument(searchModelJson != null);

        UserSafePayTransStatSearchModel searchModel = SerializationUtil.str2Object(searchModelJson, UserSafePayTransStatSearchModel.class);
        long count = userSafePayTransStatManager.searchCount(searchModel);
        if (count >= 10000L){
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "记录超过10000条，无法导出");
        }
        List<UserSafePayTransStat> userSafePayTransStatList = userSafePayTransStatManager.list(searchModel);

        // 定义一个Map，往里面放入要在模板中显示数据
        Map<String, Object> model = new HashMap<>();

        model.put("records", userSafePayTransStatList);

        String fileName = "安全付转账统计记录2.xlsx";
        String template = "/excel/tpl/安全付转账统计记录2.xls";

        InputStream is;
        try {
            //获取模板流
            is = getClass().getResourceAsStream(template);

            //火狐游览器中文文件名会有乱码,兼容火狐
            String agent = request.getHeader("USER-AGENT").toLowerCase();

            if (!Strings.isNullOrEmpty(agent) && (agent.contains("firefox") || agent.contains("safari"))) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            JxlsUtils.exportExcel(is, response.getOutputStream(), model);
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("export error", e);
        }
        return new ResultData<>();
    }

}